package com.sinodata.bsm.cicp.finder.sco;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * Description: sco平台,网络自我发现程序
 * 程序返回：物理接口名
 */

public class ScoNet extends ScoFinder {

    private static final Logger logger = Logger.getLogger(ScoNet.class);
    private static final String SHELL = "netstat -i";
    String strPattern = "(\\S+)\\s+(\\d+)\\s+(\\S+)\\s+(\\S+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)(.*)";

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] netInfo = null;
        BufferedReader reader = null;
        String strLine = null;
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            Pattern pattern = Pattern.compile(strPattern);
            while ((strLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    String netName = matcher.group(1);
                    netInfo = new String[4];
                    list.add(netInfo);
                    netInfo[0] = netName;
                    netInfo[1] = netName;
                    netInfo[2] = getHostName(ip) + " Net Interface " + netName;
                    netInfo[3] = netName; //物理接口名
                }
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to find sco net", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }

}
